import {
    baseUrl
} from './api.config.js'
import qs from 'qs'

/**
 * 拼接字符串方法
 */
var urlEncode = function(param, key, encode) {
    // param['userId'] = '1'
    if (param == null) return '';
    var paramStr = '';
    var t = typeof(param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
};

export default function(url, params, methodType = 'GET') {
    if (methodType == 'GET') {
        let dataStr = urlEncode(params).substr(1); //数据拼接字符串
        if (dataStr !== '') {
            url = url + '?' + dataStr;
        }
		console.log(url)
        return new Promise((resolve, reject) => {
            uni.request({
                method: "GET",
                url: baseUrl + url,
				header: { 'content-type': 'application/x-www-form-urlencoded' },
                success: function(res) {					
                    resolve(res.data)
                },
                fail: function(err) {
                    reject(err)
                }
            })
        })
    } else if (methodType === 'POST' || methodType === 'post') {
        let header = { 'content-type': 'application/json' }
        if (methodType === 'POST') {
            params = qs.stringify(params)
            header = { 'content-type': 'application/x-www-form-urlencoded' }
        }
        return new Promise((resolve, reject) => {
            uni.request({
                method: "POST",
                url: baseUrl + url,
                header: header,
                data: params,
                success: function(res) {
                    console.log('成功')
                    resolve(res)
                },
                fail: function(err) {
                    console.log('失败')
                    reject(err)
                }
            })
        })
    }
}